<template>
    <van-sticky>
        <van-nav-bar title="购物车" left-text="返回" left-arrow @click-left="onClickLeft" v-if="action === 'cart'" />
        <van-nav-bar title="购物车" v-else> </van-nav-bar>
    </van-sticky>

    <!-- 复选框的组别 -->
    <van-checkbox-group v-model="checked" ref="CheckboxGroup">
        <!-- 侧滑块 -->
        <van-swipe-cell v-for="(item, index) in list" :key="item.id">
            <van-card :title="item.product.name" :price="item.total">
                <!-- 商品封面图 -->
                <template #thumb>
                    <van-checkbox :name="item.id" @click="onChecked">
                    </van-checkbox>
                    <van-image width="88" fit="cover" :src="item.product.thumb_cdn" />
                </template>

                <!-- 商品数量 -->
                <template #num>
                    <van-stepper v-model="item.nums" :max="item.product.stock"
                        @change="onChange(item.nums, item.id, index)" theme="round" button-size="22" disable-input />
                </template>

                <!-- 描述 -->
                <template #desc>
                    <span>商品单价：￥{{ item.price }}</span>
                </template>
            </van-card>

            <!-- 删除 -->
            <template #right>
                <van-button square text="删除" type="danger" class="delete-button" @click="onDel(item.id, index)" />
            </template>
        </van-swipe-cell>
    </van-checkbox-group>

    <!-- 提交动作栏 -->
    <van-submit-bar :class="action === 'cart' ? '' : 'm-b-50'" :price="total" button-text="提交订单" @submit="ToOrderConfirm">
        <van-checkbox v-model="CheckedAll" :indeterminate="isIndeterminate" @change="onToggle">全选</van-checkbox>
    </van-submit-bar>

    <div class="height50"></div>
    <div :class="action === 'cart' ? '' : 'height50'"></div>

    <!-- 底部导航栏 -->
    <Footer v-if="!action" :class="action === 'cart' ? '' : 'topfooter'" />
</template>

<script setup>
const { proxy } = getCurrentInstance();
import Footer from "@/components/common/Footer.vue";
import { computed, onBeforeMount } from "vue";

//获取从商品页面跳转过来的商品id
const action = ref(proxy.$route.query.action ? proxy.$route.query.action : "");

// 选中的购物车
const checked = ref([]);

// 复选框组实例
const CheckboxGroup = ref(null);

// 全选
const CheckedAll = ref(false);

// 全选按钮不确认状态
const isIndeterminate = ref(false);

const list = ref([]);

onBeforeMount(() => {
    getCartData();
})

const total = computed(() => {
    let total = 0;
    if (checked.value.length > 0) {
        for (let item of list.value) {
            if (checked.value.includes(item.id)) {
                total += parseFloat(item.total);
            }
        }
    }

    return total * 100;
})

// 跳转订单结算
const ToOrderConfirm = () => {
    if (checked.value.length <= 0) {
        proxy.$NotifyWarn('请选择要结算的商品');

        return false;
    }

    let cartids = checked.value.join(',');

    proxy.$router.push({ path: '/product/order/confirm', query: { cartids: cartids } });
}

//选中商品
const onChecked = () => {
    if (checked.value.length === list.value.length) {
        isIndeterminate.value = false;
        CheckedAll.value = true;
    } else if (checked.value.length <= 0) {
        CheckedAll.value = false;
        isIndeterminate.value = false;
    } else {
        isIndeterminate.value = true;
    }
}

// 全选操作
const onToggle = () => {
    if (checked.value.length === list.value.length) {
        CheckboxGroup.value.toggleAll(false);
        isIndeterminate.value = false;
        CheckedAll.value = false;
    } else {
        CheckedAll.value = true;
        CheckboxGroup.value.toggleAll(true);
        isIndeterminate.value = false;
    }
}

//增加商品数量
const onChange = async (nums, cartid, index) => {
    let params = {
        nums,
        cartid,
        busid: proxy.$business.value.id
    }

    let result = await proxy.$post({
        url: '/product/cart/edit',
        params
    })

    if (result.code === 1) {
        list.value[index].total = (parseFloat(list.value[index].price) * nums).toFixed(2);  //toFixed(2)保留两位小数
    } else {
        proxy.$NotifyWarn(result.msg);

        return false;
    }
}

// 删除记录
const onDel = (cartid, index) => {
    proxy.$showConfirm({
        title: "删除",
        message: "是否删除该记录"
    }).then(async () => {
        let params = {
            cartid,
            busid: proxy.$business.value.id
        }

        let result = await proxy.$post({
            url: '/product/cart/del',
            params
        })

        if (result.code === 1) {
            proxy.$NotifySuccess({
                msg: result.msg,
                onClose: () => {
                    // 根据index索引删除数组里的元素
                    list.value.splice(index, 1);
                }
            })

            return false;
        } else {
            proxy.$NotifyWarn(result.msg);

            return false;
        }

    }).catch((err) => {

    });
}

// 结算
const confirm = () => {

}

// 获取当前登录用户的购物车所有的数据
const getCartData = async () => {
    let params = {
        busid: proxy.$business.value.id,
        source:0
    }

    let result = await proxy.$post({
        url: '/product/cart/index',
        params
    })

    if (result.code === 1) {
        list.value = result.data;

        return false;
    } else {
        proxy.$NotifyWarn(result.msg);

        return false;
    }
}
//返回上一级
const onClickLeft = () => {
    proxy.$router.back();
};
</script>

<style>
.height50 {
    margin-bottom: 50px;
}

.m-b-50 {
    margin-bottom: 50px;
    margin-top: 30px;
}

.goods-card {
    margin: 0;
    background-color: #fff;
}

.delete-button {
    height: 100%;
}

.van-card__thumb {
    display: flex;
    width: auto;
    margin-right: 15px;
}

.van-card__thumb img {
    margin-left: 5px;
}

.topfooter {
    margin-top: 100px;
}
</style>